package com.servlet;

import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.servlet.action.Action;
import com.servlet.action.ActionFactory;

/**
 * Servlet implementation class ActionDispatcher
 * 
 */
@WebServlet("/ActionDispatcher")
public class ActionDispatcher extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ActionDispatcher() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    //重载init函数, 创建聊天信息
    public void init() {
    	ServletContext application = this.getServletContext();
    	String message = "";   	
    	application.setAttribute("message", message);
    		
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 * 服务解析,使用动作框架,根据不同的请求类型生成不同的Action,以完成请求
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		request.getSession();//创建会话
		
		ActionFactory factory = new ActionFactory();//创建动作工厂,使用反射根据字符串返回相应动作类
		String actionName = request.getParameter("action");
		
		Action action = factory.create(actionName);//根据字符串返回相应动作类
		String url = action.perform(request, response);//执行请求,返回URL,若无需跳转返回空串
		
		if(url!="")
			request.getRequestDispatcher(url).forward(request, response);		
	}
	
}
